from flask import Blueprint, request
from service.share_189_service import Share189Service
from utils.api_response import ApiResponse
from typing import List, Dict, Any

share_189_bp = Blueprint('share189', __name__, url_prefix='/api')
share_189_service = Share189Service()

@share_189_bp.route('/share189/add', methods=['POST'])
def add_share_codes():
    """批量添加分享码"""
    try:
        data = request.get_json()
        if not data or 'shareItems' not in data:
            return ApiResponse.validation_error("缺少shareItems参数")
        
        share_items = data['shareItems']
        if not isinstance(share_items, list) or not share_items:
            return ApiResponse.validation_error("shareItems必须是非空数组")
        
        # 验证每个分享码项目
        for item in share_items:
            if not isinstance(item, dict):
                return ApiResponse.validation_error("shareItems中的每个项目必须是对象")
            if not item.get('shareCode'):
                return ApiResponse.validation_error("分享码不能为空")
            
            # 验证分享码格式
            if not share_189_service.validate_share_code_format(item['shareCode']):
                return ApiResponse.validation_error(f"分享码格式无效: {item['shareCode']}")
        
        # 限制批量添加数量
        if len(share_items) > 100:
            return ApiResponse.validation_error("单次最多添加100个分享码")
        
        result = share_189_service.add_share_codes(share_items)
        return ApiResponse.success(result, "分享码添加成功")
        
    except ValueError as e:
        return ApiResponse.validation_error(str(e))
    except Exception as e:
        return ApiResponse.server_error(f"添加分享码失败: {str(e)}")

@share_189_bp.route('/share189/list', methods=['GET'])
def get_share_list():
    """获取分享码列表"""
    try:
        # 获取查询参数
        status = request.args.get('status', type=int)
        keyword = request.args.get('keyword', '').strip()
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('pageSize', 20, type=int)
        
        # 参数验证
        if status is not None and status not in [0, 1, 2, 3, 4]:
            return ApiResponse.validation_error("无效的状态值，支持的状态: 0-待解析，1-解析中，2-解析成功，3-解析失败，4-已导入")
        
        if page < 1:
            page = 1
        if page_size < 1 or page_size > 100:
            page_size = 20
        
        # 如果keyword为空字符串，设为None
        if not keyword:
            keyword = None
        
        result = share_189_service.get_share_list(status, keyword, page, page_size)
        return ApiResponse.success(result, "获取分享码列表成功")
        
    except Exception as e:
        return ApiResponse.server_error(f"获取分享码列表失败: {str(e)}")

@share_189_bp.route('/share189/<int:share_id>', methods=['GET'])
def get_share_detail(share_id: int):
    """获取分享码详情"""
    try:
        result = share_189_service.get_share_detail(share_id)
        return ApiResponse.success(result, "获取分享码详情成功")
        
    except ValueError as e:
        return ApiResponse.not_found(str(e))
    except Exception as e:
        return ApiResponse.server_error(f"获取分享码详情失败: {str(e)}")

@share_189_bp.route('/share189/<int:share_id>/parse', methods=['POST'])
def parse_share_code(share_id: int):
    """触发解析分享码"""
    try:
        data = request.get_json() or {}
        force = data.get('force', False)
        depth = data.get('depth', 3)
        
        # 参数验证
        if not isinstance(force, bool):
            return ApiResponse.validation_error("force参数必须是布尔值")
        
        if not isinstance(depth, int) or depth < 1 or depth > 10:
            return ApiResponse.validation_error("depth参数必须是1-10之间的整数")
        
        result = share_189_service.parse_share_code(share_id, force, depth)
        
        if result.get('status') == 2:  # 解析成功
            return ApiResponse.success(result, "解析成功")
        else:  # 解析失败
            return ApiResponse.error(400, "解析失败", result)
        
    except ValueError as e:
        return ApiResponse.not_found(str(e))
    except Exception as e:
        return ApiResponse.server_error(f"解析分享码失败: {str(e)}")

@share_189_bp.route('/share189/<int:share_id>/import', methods=['POST'])
def import_files(share_id: int):
    """导入文件到网盘"""
    try:
        data = request.get_json()
        if not data or 'targetFolderId' not in data:
            return ApiResponse.validation_error("缺少targetFolderId参数")
        
        target_folder_id = data['targetFolderId']
        conflict_strategy = data.get('conflictStrategy', 'rename')
        preserve_structure = data.get('preserveStructure', True)
        
        # 参数验证
        if not isinstance(target_folder_id, int):
            return ApiResponse.validation_error("targetFolderId必须是整数")
        
        if conflict_strategy not in ['rename', 'skip', 'overwrite']:
            return ApiResponse.validation_error("无效的冲突处理策略，支持: rename, skip, overwrite")
        
        if not isinstance(preserve_structure, bool):
            return ApiResponse.validation_error("preserveStructure参数必须是布尔值")
        
        result = share_189_service.import_files(
            share_id, target_folder_id, conflict_strategy, preserve_structure
        )
        
        return ApiResponse.success(result, "导入任务已启动")
        
    except ValueError as e:
        return ApiResponse.validation_error(str(e))
    except Exception as e:
        return ApiResponse.server_error(f"导入文件失败: {str(e)}")

@share_189_bp.route('/share189/<int:share_id>', methods=['DELETE'])
def delete_share_code(share_id: int):
    """删除分享码"""
    try:
        result = share_189_service.delete_share_code(share_id)
        return ApiResponse.success(result, "分享码删除成功")
        
    except ValueError as e:
        return ApiResponse.not_found(str(e))
    except Exception as e:
        return ApiResponse.server_error(f"删除分享码失败: {str(e)}")

@share_189_bp.route('/share189/statistics', methods=['GET'])
def get_statistics():
    """获取统计信息"""
    try:
        result = share_189_service.get_statistics()
        return ApiResponse.success(result, "获取统计信息成功")
        
    except Exception as e:
        return ApiResponse.server_error(f"获取统计信息失败: {str(e)}")

@share_189_bp.route('/share189/<int:share_id>/preview', methods=['GET'])
def get_file_tree_preview(share_id: int):
    """获取文件树预览"""
    try:
        max_items = request.args.get('maxItems', 100, type=int)
        
        # 参数验证
        if max_items < 1 or max_items > 1000:
            max_items = 100
        
        result = share_189_service.get_file_tree_preview(share_id, max_items)
        return ApiResponse.success(result, "获取文件树预览成功")
        
    except ValueError as e:
        return ApiResponse.not_found(str(e))
    except Exception as e:
        return ApiResponse.server_error(f"获取文件树预览失败: {str(e)}")

@share_189_bp.route('/share189/preview-code', methods=['POST'])
def preview_share_code():
    """预览分享码（不存储到数据库）"""
    try:
        data = request.get_json()
        if not data:
            return ApiResponse.validation_error("缺少请求数据")
        
        share_code = data.get('shareCode', '').strip()
        access_code = data.get('accessCode', '').strip()
        depth = data.get('depth', 3)
        
        # 参数验证
        if not share_code:
            return ApiResponse.validation_error("分享码不能为空")
        
        if not share_189_service.validate_share_code_format(share_code):
            return ApiResponse.validation_error(f"分享码格式无效: {share_code}")
        
        if not isinstance(depth, int) or depth < 1 or depth > 10:
            return ApiResponse.validation_error("depth参数必须是1-10之间的整数")
        
        result = share_189_service.preview_share_code(share_code, access_code, depth)
        return ApiResponse.success(result, "分享码预览成功")
        
    except Exception as e:
        return ApiResponse.server_error(f"预览分享码失败: {str(e)}")

# 错误处理
@share_189_bp.errorhandler(404)
def not_found(error):
    return ApiResponse.not_found("接口不存在")

@share_189_bp.errorhandler(405)
def method_not_allowed(error):
    return ApiResponse.error(405, "请求方法不允许", None)

@share_189_bp.errorhandler(500)
def internal_error(error):
    return ApiResponse.server_error("服务器内部错误")